//
//  HEAIAudioView.m
//  HealthFamily
//
//  Created by LOOK on 2021/1/3.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HEAIAudioView.h"
#import "SpectrumView.h"
#import "HESpeechListener.h"
#import "HETimerWeakTarget.h"

/// 标题栏高度（包括确定/取消，和年/月/日）
#define KAlterHeight 350

/// 主题颜色
#define kThemeColor [UIColor blueColor]

@interface HEAIAudioView ()

// 中间标题
@property (nonatomic, strong) UILabel *titleLabel;

// 内容
@property (nonatomic, strong) QMUITextView *textView;

// 蒙层视图
@property (nonatomic, strong) UIView *maskView;

// 弹出背景视图
@property (nonatomic, strong) UIView *alertView;

// 语音音频动画
@property (nonatomic, strong) SpectrumView *spectrumView;

// 一键呼救
@property (nonatomic, strong) QMUIFillButton *finishBtn;

// 关闭按钮
@property (nonatomic, strong) UIButton *closeBtn;

// 动画定时器
@property (nonatomic, strong) NSTimer *timer;

// 超过3秒自动检索
@property (nonatomic, strong) NSTimer *checkTimer;

@property (nonatomic, assign) NSInteger checkTimeCnt;

@end

@implementation HEAIAudioView



- (void)show {
     
    [self initUI];
     
    UIWindow *keyWindow = BRGetKeyWindow();
    [keyWindow addSubview:self];
    // 动画前初始位置
    CGRect rect = self.alertView.frame;
    rect.origin.y = self.bounds.size.height;
    self.alertView.frame = rect;
    // 弹出动画
    self.maskView.alpha = 1;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = self.alertView.frame;
        rect.origin.y -= BR_BOTTOM_MARGIN + KAlterHeight;
        self.alertView.frame = rect;
    } completion:^(BOOL finished) {
        [self startSpeakClick];
    }];
}

- (void)initUI {
    self.frame = [UIScreen mainScreen].bounds;
    // 设置子视图的宽度随着父视图变化
    self.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    [self addSubview:self.maskView];
    
    [self addSubview:self.alertView];
    
    [self.alertView addSubview:self.titleLabel];

    [self.alertView addSubview:self.textView];
    
    [self.alertView addSubview:self.spectrumView];
    
    [self.alertView addSubview:self.finishBtn];
    
    [self.alertView addSubview:self.closeBtn];

    [self startTime];
}

#pragma mark -
#pragma mark - 蒙层视图
- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2f];
        // 设置子视图的大小随着父视图变化
        _maskView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _maskView.userInteractionEnabled = YES;
        UITapGestureRecognizer *myTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapMaskView:)];
        [_maskView addGestureRecognizer:myTap];
    }
    return _maskView;
}

#pragma mark - 弹框视图
- (UIView *)alertView {
    if (!_alertView) {
        _alertView = [[UIView alloc]initWithFrame:CGRectMake(0, self.bounds.size.height - KAlterHeight - BR_BOTTOM_MARGIN, self.bounds.size.width,  BR_BOTTOM_MARGIN + KAlterHeight)];
        _alertView.backgroundColor = [UIColor whiteColor];
        _alertView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
        
        [_alertView hg_setCornerOnTopWithRadius:10];
    }
    return _alertView;
}

#pragma mark - 中间标题label
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 15, self.bounds.size.width, 44)];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = DYFont(22);
        _titleLabel.textColor = [UIColor darkGrayColor];
        _titleLabel.text = @"请说，我在聆听...";
    }
    return _titleLabel;
}

#pragma mark - 语音识别内容
- (QMUITextView *)textView {
    if (!_textView) {
        _textView = [QMUITextView new];
        // 限制可输入的字符长度
        _textView.maximumTextLength = 1500;
        _textView.font = DYFont(17);
        _textView.placeholder = @"您可以试试这样说：找医生";
        _textView.placeholderColor = CNavSubTitleColor; // 自定义 placeholder 的颜色
        _textView.textContainerInset = UIEdgeInsetsMake(5, 7, 5, 7);
        _textView.typingAttributes = @{NSFontAttributeName: DYFont(17),
                                           NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:20]
        };
        _textView.scrollEnabled = NO;
        _textView.backgroundColor = KWhiteColor;
        _textView.userInteractionEnabled = NO;
        [self.alertView addSubview:_textView];
        [_textView setDelegate:self];
        
        [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleLabel.mas_bottom).mas_offset(10);
            make.left.equalTo(self.alertView).mas_offset(30);
            make.right.equalTo(self.alertView).mas_offset(-30);
            make.height.mas_greaterThanOrEqualTo(80);
        }];
    }
    return _textView;
}

#pragma mark - 语音音频动画
- (SpectrumView *)spectrumView {
    if (!_spectrumView) {
//        _spectrumView = [[SpectrumView alloc] initWithFrame:CGRectMake(30 , 40, KScreenWidth - 60, 60.0)];
        
        _spectrumView = [SpectrumView new];
    //    _spectrumView.text = [NSString stringWithFormat:@"%d",0];
        _spectrumView.middleInterval = 0;
//        _spectrumView.numberOfItems = 12;
        __weak SpectrumView * weakSpectrum = _spectrumView;

 
//        _spectrumView.itemLevelCallback = ^() {
////            weakSpectrum.level = -160;
//        };
        [self.alertView addSubview:_spectrumView];
        
        [_spectrumView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.textView.mas_bottom).mas_offset(10);
            make.left.equalTo(self.alertView).mas_offset(30);
            make.right.equalTo(self.alertView).mas_offset(-30);
            make.height.mas_greaterThanOrEqualTo(60);
        }];
    }
    return _spectrumView;
}

#pragma mark - 动画定时器

- (void)startTime {
    [self.timer fire];
}

- (void)stopTime {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [HETimerWeakTarget scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeHandler) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (void)timeHandler {
//    NSArray *arr = @[@"22.459337", @"27.184845", @"30.021973", @"34.590576", @"28.462954", @"33.111614", @"40.974174"];
    NSArray *arr = @[@"22.459337", @"27.184845", @"30.021973", @"34.590576", @"28.462954", @"33.111614", @"40.974174"];
  
    int y = 0 +  (arc4random() % (arr.count)); // [0 , 160]
    NSString *value = arr[y];
//    DLog(@"i %ld   %f", y, value.floatValue)
    self.spectrumView.level = -value.floatValue;
}

#pragma mark - 自动检索定时器
- (NSTimer *)checkTimer {
    if (!_checkTimer) {
        _checkTimer =  [HETimerWeakTarget scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkTimeHandler) userInfo:nil repeats:YES];
    }
    return _checkTimer;
}

- (void)startCheck {
    self.checkTimeCnt = 3;
    [self.checkTimer fire];
}

- (void)stopCheck {
    if (_checkTimer) {
        [_checkTimer invalidate];
        _checkTimer = nil;
    }
}

- (void)checkTimeHandler {
    NSInteger cnt = self.checkTimeCnt--;
    if (cnt == 0) {
        [self stopCheck];
        if (self.finishBlock) {
            NSString *searchString = [[_textView.text componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];
            self.finishBlock(searchString);
        }
        [self dismiss];
    }
}

#pragma mark -  一键呼救
- (QMUIFillButton *)finishBtn {
    if (!_finishBtn) {
        _finishBtn = [[QMUIFillButton alloc] initWithFillColor:CNavBgColor titleTextColor:CNavBgFontColor];
        _finishBtn.titleLabel.font = UIFontMake(16);
        [_finishBtn setTitle:@"一键呼救" forState:UIControlStateNormal];
        [self.alertView addSubview: _finishBtn];
        
        [_finishBtn addTarget:self action:@selector(finishClick) forControlEvents:UIControlEventTouchUpInside];
        
        [_finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.alertView.mas_bottom).mas_offset(-30);
            make.width.offset(130);
            make.height.offset(40);
            make.centerX.equalTo(self.alertView);
        }];
    }
    return _finishBtn;
}

#pragma mark -
- (UIButton *)closeBtn {
    if(!_closeBtn) {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setImage:IMAGE_NAMED(@"good_pop_close") forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        [self.alertView addSubview:_closeBtn];
        
        [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.alertView).mas_offset(15);
            make.right.equalTo(self.alertView).mas_offset(-15);
            make.width.height.offset(40);
        }];
    }
    return _closeBtn;
}



- (void)finishAudioSearchHandler:(finishAudioHandler)block {
    self.finishBlock = block;
}

#pragma mark -

- (void)finishClick {
    [DYTools callPhone:@"0731-84325010"];
    [self dismiss];
}

- (void)startSpeakClick {
    KWeakSelf
    if (@available(iOS 10.0, *)) {
        HESpeechListener *sp = [HESpeechListener sharedManager];
        [sp startRecognizer];
        
        sp.textBlock = ^(NSString * _Nonnull text, BOOL status) {
            if (status) {
                weakSelf.textView.text = text;
            }else {
            }
            [weakSelf stopCheck];
            [weakSelf startCheck];
        };
    } else {
        // Fallback on earlier versions
    }
}

- (void)stopSpeakClick {
    if (@available(iOS 10.0, *)) {
        [[HESpeechListener sharedManager] endRecognizer];
    } else {
        // Fallback on earlier versions
    }
}

#pragma mark - 点击蒙层视图事件
- (void)didTapMaskView:(UITapGestureRecognizer *)sender {
//    [self dismiss];
}

#pragma mark - 关闭选择器视图
- (void)dismiss {
    // 关闭动画
    [UIView animateWithDuration:0.2 animations:^{
        CGRect rect = self.alertView.frame;
        rect.origin.y +=  BR_BOTTOM_MARGIN + KAlterHeight;
        self.alertView.frame = rect;
        self.maskView.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [self stopSpeakClick];
        [self stopTime];
        [self stopCheck];
    }];
}


@end
